<template>
  <div style="display: flex; align-items: center;position: relative;">
    <label for="inputId" :style="{'color': 'aliceblue', 'width': labelWidth}">{{ label }}</label>
    <input id="inputId" v-model="inputValue" @input="handleInput" @blur="hideOptions" :style="{width: inputWidth}"/>
    <ul :style="{ display: showOptions ? 'block' : 'none',left:labelWidth,width:inputWidth}">
      <li v-for="(option, index) in filteredOptions" :key="index" @click="selectOption(option)">
        {{ option.label }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  props: {
    options: {
      type: Array
    },
    value: {
      type: String
    },
    label: {
      type: String,
      default: ''
    },
    labelWidth: {
      default: '70px'
    },
    inputWidth: {
      type: String,
      default: '200px'
    }
  },
  name: 'AutoCompleteInput',
  data() {
    return {
      inputValue: '',
      showOptions: false
    }
  },
  watch: {
    inputValue() {
      this.$emit("input", this.inputValue)
    },
    value() {
      this.inputValue = this.value
    }
  },
  mounted() {
    this.inputValue = this.value
  },
  computed: {
    filteredOptions() {
      return this.options.filter(option =>
          option.label.toLowerCase().includes(this.inputValue.toLowerCase())
      )
    }
  },
  methods: {
    handleInput() {
      this.showOptions = true
    },
    hideOptions() {
      const ul = this.$el.querySelector('ul')
      ul.style.opacity = '0'
      setTimeout(() => {
        this.showOptions = false
        ul.style.opacity = '1'
      }, 200)
    },
    selectOption(option) {
      this.inputValue = option.value
      this.showOptions = false
    }
  }
}
</script>

<style scoped>
input {
  background-color: #0a1c3b;
  color: #fff;
  font-family: Arial, sans-serif;
  font-size: 16px;
  padding: 10px;
  cursor: text;
  height: 40px;
  border: 2px solid #00b3ff;
  border-radius: 5px;
  -webkit-appearance: none;
  -moz-appearance: none;
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
  background-color: #00b3ff;
  border: 2px solid #00b3ff;
  border-top: none;
  border-radius: 0 0 5px 5px;
  position: absolute;
  top: 44px;
  right: 0;
  z-index: 1;
  transition: opacity 0.2s ease-out;
}

li {
  padding: 10px;
  cursor: pointer;
}

li:hover {
  background-color: #eee;
}
</style>